package com.iflytek.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iflytek.entity.SignInRecord;
import com.iflytek.entity.Student;
import com.iflytek.mapper.SignInRecordMapper;
import com.iflytek.service.ISignInRecordService;
import com.iflytek.service.IStudentService;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.iai.v20200303.IaiClient;
import com.tencentcloudapi.iai.v20200303.models.Candidate;
import com.tencentcloudapi.iai.v20200303.models.SearchFacesRequest;
import com.tencentcloudapi.iai.v20200303.models.SearchFacesResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Base64;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 周超
 * @since 2025-05-29
 */
@Slf4j
@Service
public class SignInRecordServiceImpl extends ServiceImpl<SignInRecordMapper, SignInRecord> implements ISignInRecordService {
    @Resource
    private IStudentService studentService;

    @Override
    public Student recordSignIn(MultipartFile file) {
        Student student = null;
        try {
            //先根据该张图片进行搜索人脸，找到personId
            String personId = searchPersonIdByFace(file);
            student = studentService.findByPersonId(personId);
            if (student == null) {
                log.warn("未找到对应的学生信息，personId: {}", personId);
                return null;
            }
            SignInRecord signInRecord = new SignInRecord();
            signInRecord.setStudentId(student.getId());
            signInRecord.setRecordTime(LocalDateTime.now());
            this.save(signInRecord);
        } catch (Exception e) {
            log.error("签到记录失败: {}", e.getMessage(), e);
            return null;
        }
        log.info("签到记录成功");
        return student;
    }

    private String searchPersonIdByFace(MultipartFile file) {
        //创建腾讯云人员库中的人员信息
        Credential credential = new Credential("AKIDkMlxvf9PSuEOL6e095oKelfNuERREpCQ", "ADJJNM8mPuCIML9yazAA250mMwSnz0ws");
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("iai.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        IaiClient client = new IaiClient(credential, "ap-nanjing", clientProfile);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        SearchFacesRequest req = new SearchFacesRequest();
        req.setGroupIds(new String[]{"zjjxy_2025_zyzhsx"});
        try {
            // 获取文件字节数组并转为Base64编码
            byte[] fileBytes = file.getBytes();
            String base64Image = Base64.getEncoder().encodeToString(fileBytes);
            // 设置Base64编码的图片数据
            req.setImage(base64Image);

            log.info("搜索学生人脸信息请求：{}", AbstractModel.toJsonString(req));
            // 返回的resp是一个CreateFaceResponse的实例，与请求对象对应
            SearchFacesResponse resp = client.SearchFaces(req);
            // 输出json格式的字符串回包
            log.info("搜索学生人脸信息响应：{}", AbstractModel.toJsonString(resp));
            // 返回第一个候选人的personId
            Candidate candidate = resp.getResults()[0].getCandidates()[0];
            if (candidate.getScore() > 80) {
                log.info("找到匹配的学生人脸信息，personId: {}", candidate.getPersonId());
                return candidate.getPersonId();
            } else {
                log.warn("未找到匹配的学生人脸信息，得分: {}", candidate.getScore());
                throw new RuntimeException("未找到匹配的学生人脸信息");
            }
        } catch (Exception e) {
            log.info("搜索学生人脸信息失败: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
